package thread_pool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/23
 * Time:12:19
 * initialValue初始化threadLocal
 **/
public class PoolDemo24 {
    static ThreadLocal<String> threadLocal = new ThreadLocal() {
        @Override
        protected String initialValue() {
            System.out.println("执行了初始化方法");
            return "java";
        }
    };

    public static void main(String[] args) {
        /*String result = threadLocal.get();
        System.out.println("从threadLocal读取到"+result);*/

        //判断是执行一次还是多次
        //多次，threadLocal是程序级别的私有变量
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                1, 1, 0, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000)
        );
        for (int i = 0; i < 2; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    String result = threadLocal.get();
                    System.out.println("得到数据" + result);
                }
            });
        }
    }
}
